package org.hefan.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("token");
        // 如果token不为null
        if (token != null) {
            // 通过key值token 获取value值logininfo
            // obj就是logininfo
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null) { // 表示登录了,并且没有过期
                // 重新设置过期时间
                redisTemplate.opsForValue().set(token, obj, 30, TimeUnit.MINUTES);
                return true;
            }
        }
        //跳转登录页面
        response.setCharacterEncoding("UTF-8");
        //告诉浏览器我要给你响应一个json数据，用Utf-8编码
        response.setContentType("application/json;charset=UTF-8");
        // 把这个字符串响应到前端
        response.getWriter().write("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
